import React, { FC, RefObject, DragEvent } from 'react';
import styles from '../index.less';
import { Row, Col } from 'antd';
import Card from '../Card';
import { items } from '../constants';

interface IComponents {
    currentDraggableRef: RefObject<any>
}
const Components: FC<IComponents> = (props) => {
    const { currentDraggableRef } = props;
    const isHasMoreEle = (items.length % 2) > 0;

    const onHandleDrag = (e: DragEvent<any>) => {
        const target = e.target as HTMLElement
        currentDraggableRef.current.currentDraggable = target.dataset.cardtype + "_" + Date.now();
        e.dataTransfer.setData("text/plain", "");
        target.style.cursor = 'pointer';
    };

    return (
        <div
            className={styles["components"]}
        >
            {
                formatDyadicArray(items).map(i => (
                    <Row 
                        justify={'center'}
                        align={'middle'}
                        gutter={8}
                        style={{ margin: '8px 0px' }}
                    >
                        {
                            i.map(v => {
                                return (
                                    <>
                                        <Col span={12}>
                                            <Card title={v.label} onHandleDrag={onHandleDrag} value={v.value}/>
                                        </Col>
                                        {i.length === 1 && <Col span={12}/>}
                                    </>
                                )
                            })
                        }
                    </Row>
                ))
            }
        </div>
    )
};


export default Components;


const formatDyadicArray = (arr) => {
    if(arr.length <= 0) return [];
    const dyadicArr = [];
    arr.forEach((i, key) => {
        if(key % 2 === 0) {
            dyadicArr.push([i]);
        } else {
            dyadicArr[dyadicArr.length - 1].push(i);
        }
    })

    return dyadicArr;
}